import jieba
from django.shortcuts import render, HttpResponse
import pymysql
import redis
from .functions import *
import json
import threading
import random
import time

# Create your views here.
# 创建MySQL连接
mysql_conn = pymysql.connect(host='127.0.0.1', user='root', password='123456', db='msquare', charset='utf8mb4')
cursor = mysql_conn.cursor(pymysql.cursors.DictCursor)

# 创建redis连接
redis_conn = redis.Redis(host='127.0.0.1', port=6389)

lock = threading.Lock()


def picture_home(request):
    return render(request, 'picture/picture.html')


def picture_show(request):
    return render(request, 'picture/picture_single.html', {'pid': request.GET.get('pid', 2),'user_id': request.session.get('user_id',-1)})


def get_pictures(request):
    '''

    :param request: 需求的图片数量、用户ID
    :return: 图集的概略信息
    '''
    result = {'status': 200, 'info': []}
    num = int(request.GET.get('num', 0))
    user_id = request.session.get('user_id', None)
    start = time.time()
    # 如果用户登录
    if user_id:
        # 将用户传入推荐系统，返回用户喜欢的4个类别
        targets = ['阿莱克斯', '天空', '米兰·库尔尼科娃', '李贤宰']

        # 从redis中查取符合4个类别的所有picture_id
        pictures_id = {-1, -2}
        for target in targets:
            pictures_id |= redis_conn.smembers(target)
        pictures_id = tuple(map(lambda x: int(x), pictures_id))

        # 查询所有picture_id, 返回指定数量
        sql = "select * from picture_t_picture where id in %s limit %d, %d" % (repr(pictures_id), num, 25)
    else:
        sql = "select * from picture_t_picture limit %d, %d" % (num, 25)

    try:
        cursor.execute(sql)
        result['info'] = cursor.fetchall()
    except:
        print(sql)
        result['status'] = 500

    return HttpResponse(json.dumps(result))


# 获取图集部分标签
def get_targets(request):
    '''

    :param request: 需求的图集标签数量、用户ID
    :return: 图集标签信息
    '''
    result = {'status': 200, 'info': {'recommend': [], 'sence': []}}
    user_id = request.session.get('user_id', None)

    # 如果用户登录，获取其喜欢的4个标签, 否则随机从场景和人物中各取两个推荐
    if user_id:
        # 将用户传入推荐系统，返回用户喜欢的4个类别
        targets = [4, 5, 1887, 1888]
    else:
        targets = random.sample(range(1887, 1912), 2) + random.sample(range(1, 1816), 2)
    sql = "select * from picture_t_picture_target where id in %s" % repr(tuple(targets))
    try:
        cursor.execute(sql)
        result['info']['recommend'] += cursor.fetchall()
    except:
        print(sql)
        result['status'] = 500

    # 获取所有的场景标签
    sql = "select * from picture_t_picture_target where type=1"
    try:
        cursor.execute(sql)
        result['info']['sence'] += cursor.fetchall()
    except:
        print(sql)
        result['status'] = 500

    return HttpResponse(json.dumps(result))


# 热门图片评论
def hot_picture_comment(request):
    '''

    :param request: num
    :return: 图片ID 图片封面 图片名称 评论ID 用户ID 用户名 评论时间 评论信息
    '''

    # 从请求中取出当前评论数量
    num = int(request.GET.get('num', 0))

    # 查询热门图片评论，以点赞数排序
    sql = 'select t1.id img_id, t1.url img_url, t1.movie_name, t2.user_id, t2.username, t2.time, t2.id comment_id, ' \
          't2.content from picture_t_picture t1, user_t_comment t2 where t1.id = t2.media_id and t2.type = 1 ' \
          'and t2.reply_id = -1 order by t2.parise_num desc limit %d,%d' % (num, 5)
    result = {'status': 200}
    comment_info = {}
    try:
        cursor.execute(sql)
        comment_info = cursor.fetchall()
        for item in comment_info:
            item['time'] = str(item['time'])
    except:
        result['status'] = 403
    result['info'] = comment_info
    return HttpResponse(json.dumps(result))


# 图片详情页评论--时间排序
def picture_comment_time(request):
    '''

    :param request: num, picture_id
    :return: 评论ID 用户ID 图片ID 用户头像 用户名 评论时间 评论内容 点赞数 评论数
    '''

    # 从请求中取出图片id，当前评论数量
    picture_id = int(request.GET.get('picture_id'))
    num = int(request.GET.get('num', 0))

    # 查询图片评论，返回指定数量
    sql = 'select t2.id comment_id, t2.user_id, t1.id img_id, t3.avatar, t3.username, t2.time, t2.content, ' \
          't2.parise_num, t2.comment_num from picture_t_picture t1, user_t_comment t2, user_t_user t3  where ' \
          't1.id = t2.media_id and t2.type = 1 and t2.user_id = t3.id and t2.reply_id= -1 and t2.media_id = %d ' \
          'order by t2.time desc limit %d,%d' % (picture_id, num, 5)
    result = {'status': 200}
    comment_info = {}
    try:
        cursor.execute(sql)
        comment_info = cursor.fetchall()
        for item in comment_info:
            item['time'] = str(item['time'])
    except:
        result['status'] = 403
    result['info'] = comment_info
    return HttpResponse(json.dumps(result))


# 图片详情页评论--点赞排序
def picture_comment_parise(request):
    '''

    :param request: num, picture_id
    :return: 评论ID 用户ID 图片ID 用户头像 用户名 评论时间 评论内容 点赞数 评论数
    '''

    # 从请求中取出图片id，当前评论数量
    picture_id = int(request.GET.get('picture_id'))
    num = int(request.GET.get('num', 0))

    # 查询图片评论，返回指定数量
    sql = 'select t2.id comment_id, t2.user_id, t1.id img_id, t3.avatar, t3.username, t2.time, t2.content, ' \
          't2.parise_num, t2.comment_num from picture_t_picture t1, user_t_comment t2, user_t_user t3  where ' \
          't1.id = t2.media_id and t2.type = 1 and t2.user_id = t3.id and t2.reply_id= -1 and t2.media_id = %d ' \
          'order by t2.parise_num desc limit %d,%d' % (picture_id, num, 5)
    result = {'status': 200}
    comment_info = {}
    try:
        cursor.execute(sql)
        comment_info = cursor.fetchall()
        for item in comment_info:
            item['time'] = str(item['time'])
    except:
        result['status'] = 403
    result['info'] = comment_info
    return HttpResponse(json.dumps(result))


# 图片详情页评论回复
def picture_comment_reply(request):
    '''

    :param request: num, comment_id
    :return: 评论回复ID 用户ID 图片ID 用户头像 用户名 评论时间 评论内容 点赞数 评论数
    '''
    comment_id = int(request.GET.get('comment_id'))
    num = int(request.GET.get('num', 0))

    # 查询图片评论回复，返回指定数量
    sql = 'select t2.id comment_reply_id, t2.reply_id, t2.user_id, t1.id picture_id, t3.avatar, t3.username, t2.time,' \
          ' t2.content, t2.parise_num, t2.comment_num from picture_t_picture t1, user_t_comment t2, user_t_user t3' \
          ' where t1.id = t2.media_id and t2.type = 1 and t3.id = t2.user_id and t2.reply_id = %d order by ' \
          't2.time desc limit %d,%d' % (comment_id, num, 5)
    result = {'status': 200}
    comment_info = {}
    try:
        cursor.execute(sql)
        comment_info = cursor.fetchall()
        for item in comment_info:
            item['time'] = str(item['time'])
    except:
        result['status'] = 403
    result['info'] = comment_info
    return HttpResponse(json.dumps(result))


# 图片搜索结果页面
def search(request):
    content = request.GET.get('content', '')
    return render(request, 'picture/search.html', {'content': content})


def movie_imgs(request):
    result = {'status': 200}
    if request.method == 'GET':
        mysql_conn = pymysql.connect(host='127.0.0.1', user='root', password='123456', db='msquare', charset='utf8mb4')
        cursor = mysql_conn.cursor(pymysql.cursors.DictCursor)
        id = request.GET.get('movie_id')
        sql = ''
        try:
            sql = "select id,url from picture_t_picture where movie_id ='%s'" % id
            cursor.execute(sql)
            data = cursor.fetchall()
            result['info'] = data
        except:
            print(sql)
            result['status'] = 500
    return HttpResponse(json.dumps(result))


# 获取该场景其他图片
def get_senceImage(request):
    result = {'status': 200, 'info': []}

    pid = request.GET.get('pid')
    sql = "select t3.id id, t3.url url from (select target_id " \
          "from picture_t_picture_class where picture_id = {0}) t1, picture_t_picture_class t2, picture_t_picture t3 " \
          "where t1.target_id = t2.target_id and t2.picture_id = t3.id and t2.picture_id != {0} limit 6".format(pid)
    try:
        lock.acquire()
        cursor.execute(sql)
        lock.release()
        result['info'] = cursor.fetchall()
    except:
        print(sql)
        result['status'] = 500

    return HttpResponse(json.dumps(result))


# 获取指定图片标签
def get_class(request):
    result = {'status': 200, 'info': []}

    pid = request.GET.get('pid')
    sql = "select t2.* from picture_t_picture_class t1, picture_t_picture_target t2 " \
          "where picture_id = %s and t1.target_id = t2.id;" % pid
    try:
        lock.acquire()
        cursor.execute(sql)
        lock.release()
        result['info'] = cursor.fetchall()
    except:
        print(sql)
        result['status'] = 500

    return HttpResponse(json.dumps(result))

#热门图片
def hot_picture(request):
    '''

    :param
    request:
    :return: result：图片信息
    '''
    # 返回热门图片信息
    mysql_conn.ping(reconnect=True)
    result = {'status': 200}
    if request.method == 'GET':
        sql = "select p1.id,p1.url,m1.score,m1.release_date,m1.information,m1.movie_name,m1.directors from picture_t_picture p1, movie_t_movie m1 where p1.movie_id = m1.id order by (p1.parise_num*2+p1.star_num*5+p1.click_num) DESC LIMIT 10"
        try:
            lock.acquire()
            cursor.execute(sql)
            lock.release()
            data = cursor.fetchall()
            result['info'] = data
        except:
            print(sql)
            result['status'] = 500
    return HttpResponse(json.dumps(result))


# 图片的下载
def download(request):
    '''

    :param request: user_id:用户id，picture_id: 图片id, type: 0: 电影, 1：图片
    :return: status: 下载成功, message: 提示
    '''

    user_id = request.session.get('user_id')
    picture_id = request.GET.get('picture_id')

    # 判断用户是否登录
    if user_id:
        # 判断用户是否已经下载过
        sql = "select * from user_t_download where user_id = %s and picture_id = %s" % (user_id, picture_id)
        try:
            cursor.execute(sql)
            if not cursor.fetchone():
                # 添加用户下载行为
                insert_sql = "insert into user_t_download (user_id, picture_id, time) values(%s, %s, now())" % (user_id, picture_id)

                cursor.execute(insert_sql)
                mysql_conn.commit()
        except Exception as e:
            print('download:', e)

    # 下载文件
    url = request.GET.get('url', None)
    if url:
        img_response = requests.get(url)
        response = HttpResponse(img_response.content)
        response['content_type'] = "application/octet-stream"
        response['Content-Disposition'] = 'attachment; filename=' + picture_id + '.jpg'

        return response

    return HttpResponse('下载失败！')
